package com.zhijiaoyun.oss;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zhijiaoyun.model.User;

/**
 * @author shisfish
 * @date 2017/12/12
 */
public class UserManager {

    public static Map<String, HttpSession> USER_SESSION = new HashMap<>();

    public static Map<String, String> USER_SESSIONID = new HashMap<>();

    public static void afterUserLogin(HttpServletRequest request, HttpServletResponse response, User user, String device) {
    	// 判断这个用户是否有session，有的话都删除
    	String newKey = "user_" + device + "_" + user.getUserId();
		 HttpSession newUserSession = USER_SESSION.get(newKey);
		 if (newUserSession != null) {
		     USER_SESSIONID.remove(newUserSession.getId());
		     USER_SESSION.remove(newUserSession);
		 }
    	
        // 不管三七二十一，先删除sessionId相关的属性。
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        String oldKey = USER_SESSIONID.get(sessionId);
        if (oldKey != null) {
            USER_SESSIONID.remove(sessionId);
            HttpSession userSession = USER_SESSION.get(oldKey);
            if (userSession != null) {
                USER_SESSIONID.remove(userSession.getId());
                USER_SESSION.remove(userSession);
            }
        }
        
        session.setAttribute("user", user);
        USER_SESSION.put(newKey, session);
        USER_SESSIONID.put(sessionId, newKey);
    }

    public static boolean checkToken(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        String oldKey = USER_SESSIONID.get(sessionId);
        if (oldKey == null) {
            // token进入的，但是没有记录，证明被删除了，需要重新登录
            return false;
        } else {
            return true;
        }
    }
}
